#!/usr/bin/env python
#coding: utf-8

import os, sys
from urllib import urlopen
from datetime import datetime
from dyndnsupdate import updateip
IP_JOURNAL = '/tmp/ip-journal.txt'

def get_current_ip():
	return urlopen('http://ip.mysokol.ru').read().strip('\n').strip(' ')

def get_last_ips(num=1):
	try:
		lines = open(IP_JOURNAL, 'r').readlines()
		ips = []
		for line in lines:
			if len(line)>6: ips.append(line.strip())
		if len(ips): return ips[-1*num:]
	except:
		return []
	
def check_ip_change():
	current_ip = get_current_ip()
	last_ips = get_last_ips(10)
	last_ip = last_ips[-1] if len(last_ips) else []
	if current_ip != last_ip:
		print "{0} IP changed! LastIP: {1} New IP: {2}".format(datetime.now(), last_ip, current_ip)
		if updateip(current_ip):
			print "IP updated successfully."
			last_ips.append(current_ip)
			save_ip_list(last_ips)
		else:
			print "Cant update IP %("
	else:
		print "{0} IP not changed: {1}".format(datetime.now(), current_ip)
	
def save_ip_list(ips):
	f = open(IP_JOURNAL, 'w')
	for ip in ips: f.write(ip+'\n')
	f.close()
	print 'last {0} ip-addresses saved.'.format(len(ips))

if __name__ == '__main__':
	check_ip_change()
